package root.electronclass.electronclass.school

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.widget.LinearLayout
import android.widget.PopupWindow
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.text.bold
import androidx.core.text.buildSpannedString
import androidx.core.text.color
import androidx.core.text.scale
import androidx.core.view.updateLayoutParams
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.RecyclerView
import retrofit2.Call
import root.electronclass.electronclass.R
import root.electronclass.electronclass.adapter.GridSpacingItemDecoration
import root.electronclass.electronclass.common.base.BasicAdapter
import root.electronclass.electronclass.common.base.ViewBindingFragment
import root.electronclass.electronclass.databinding.FragmentSchoolStudyBinding
import root.electronclass.electronclass.databinding.FragmentSchoolStudyItemBinding
import root.electronclass.electronclass.databinding.FragmentSchoolStudyItemItemBinding
import root.electronclass.electronclass.databinding.ItemPopupwindowBinding
import root.electronclass.electronclass.ext.doOnSearch
import root.electronclass.electronclass.ext.dp
import root.electronclass.electronclass.ext.tabs
import root.electronclass.electronclass.ext.toMMdd
import root.electronclass.electronclass.mvp.GlobalParameter
import root.electronclass.electronclass.mvp.base.BaseResponse
import root.electronclass.electronclass.mvp.base.CallbackNext
import root.electronclass.electronclass.mvp.entity.GroupData
import root.electronclass.electronclass.mvp.entity.LearnSpace
import root.electronclass.electronclass.mvp.entity.Subject
import root.electronclass.electronclass.mvp.rest.RestManager
import root.electronclass.electronclass.other.WebFragment
import root.electronclass.electronclass.school.model.SchoolStudyBoxModel

// TODO: Rename parameter arguments, choose names that match

class SchoolStudyFragment : ViewBindingFragment<FragmentSchoolStudyBinding>() {
    private val viewModel: SchoolStudyBoxModel by viewModels()
    private var dataType = 1
    lateinit var popupWindow: PopupWindow
    private var subjectName: String? = null
    private var subAdapter: BasicAdapter<Subject, ItemPopupwindowBinding>? = null

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if (hidden.not() && view != null) {
            viewModel.load(page = 1)
        }
    }


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val tabs = resources.getStringArray(R.array.class_tabs)
        binding.tabLayout.tabs(tabs) { tab ->
            val text = binding.search.text.toString()
            when (tab) {
                getString(R.string.class_7_day) -> dataType = 1
                getString(R.string.class_3_month) -> dataType = 2
                getString(R.string.class_current_semester) -> dataType = 3
                getString(R.string.class_all) -> dataType = 4
            }

            viewModel.load(type = dataType, subjectName = subjectName, remark = text, 1)
        }
        binding.recycler.adapter = adapter
        binding.search.doOnSearch {
            viewModel.load(type = dataType, subjectName = subjectName, remark = it, 1)
            false
        }

        viewModel.data.observe(viewLifecycleOwner) { its ->
            if (its.first == 1) {
                val list = its.second.groupBy { it.onlineTime.take(10) }
                val mapList = mutableListOf<GroupData<LearnSpace>>()
                for (i in list) {
                    mapList.add(GroupData(i.key, i.value))
                }
//                val sortedMap = mapList.sortedBy { it.createTime }
                adapter.notifyChanged(mapList)
            } else {
                val list = its.second.groupBy { it.onlineTime.take(10) }
                val mapList = mutableListOf<GroupData<LearnSpace>>()
                for (i in list) {
                    mapList.add(GroupData(i.key, i.value))
                }
//                val sortedMap = mapList.sortedBy { it.createTime }
                adapter.addAll(mapList)
            }
        }
        showPopWindow()
        getSubject()

        binding.subjectCl.setOnClickListener {
            popupWindow.showAsDropDown(binding.subjectCl)
        }

    }


    private val adapter = BasicAdapter<GroupData<LearnSpace>, FragmentSchoolStudyItemBinding> { holder, item ->
        holder.binding.vDash.updateLayoutParams<ConstraintLayout.LayoutParams> {
            topMargin = if (holder.absoluteAdapterPosition == 0) 12 else 0
        }
        holder.binding.itemTitle.text = item.createTime?.toMMdd

        val childAdapter = BasicAdapter<LearnSpace, FragmentSchoolStudyItemItemBinding> { holder1, childItem ->
            holder1.binding.picSdw.setImageURI(if (childItem.pictureFormat.isNotEmpty()) childItem.pictureFormat[0].url else "")
            holder1.binding.title.text = childItem.name
            holder1.binding.name.text = childItem.created
            holder1.binding.time.text = "发布于 ${childItem.createTime}"
            holder1.binding.tvType.text = childItem.subjectName

            holder1.binding.studyNum.text = buildSpannedString {
                bold { append("${childItem.learnNumAll}次") }
                scale(0.5f) { color(resources.getColor(R.color.c_093b5d_80, null)) { append("累计学习") } }
            }
            holder1.binding.studyDown.text = buildSpannedString {
                bold { append("${childItem.downloadNumAll}次") }
                scale(0.5f) { color(resources.getColor(R.color.c_093b5d_80, null)) { append("累计下载") } }
            }

            holder1.binding.tvBtn.setOnClickListener {
                WebFragment.startWeb(requireActivity(), WebFragment.SCHOOL_PROPAGANDA.format(childItem.id))
            }
        }
        holder.binding.itemRecycler.addItemDecoration(GridSpacingItemDecoration(1, 24, false))
        holder.binding.itemRecycler.adapter = childAdapter
        childAdapter.refresh(item.list)
    }


    private fun showPopWindow() {
        //自定义布局，作为PopupWindow显示的内容
        val contentView = LayoutInflater.from(requireActivity()).inflate(R.layout.pop_window, null);
        popupWindow = PopupWindow(contentView, LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, true)
        val recyclerView = contentView.findViewById<RecyclerView>(R.id.recycler)
        subAdapter = BasicAdapter<Subject, ItemPopupwindowBinding> { holder, item ->
            holder.binding.tv.text = item.subjectName
            holder.binding.tv.setOnClickListener {
                subjectName = item.subjectName
                binding.subjectTv.text = item.subjectName
                if (subjectName == "全部") {
                    subjectName = ""
                }
                viewModel.load(type = dataType, subjectName = subjectName, remark = binding.search.text.toString(), 1)
                popupWindow.dismiss()
            }
        }
        recyclerView.adapter = subAdapter
        popupWindow.isTouchable = true
        popupWindow.setTouchInterceptor { p0, p1 -> false };
    }


    private fun getSubject() {
        RestManager.getInstance().initRest().subjectList().enqueue(object : CallbackNext<BaseResponse<List<Subject>>>(mDialogViewModel) {
            override fun onSuccessful(call: Call<BaseResponse<List<Subject>>>, response: BaseResponse<List<Subject>>) {
                if (response.isSuccess) {
                    val list = arrayListOf<Subject>(Subject(0, "全部", GlobalParameter.getSchoolInfo().schoolId))
                    list.addAll(response.rows)
                    subAdapter?.refresh(list)
                }
            }

            override fun onError(call: Call<BaseResponse<List<Subject>>>, response: BaseResponse<List<Subject>>) {
            }
        })
    }

}